<?php

/**
 * 产品详细信息
 * @author:zhulin
 * @since:1012 4.17
 * 
 */
class Product_Detail {
    /**
     * 数据表名称
     */
    const TABLE_NAME = 'productinfo';
    const TABLE_NAME_SEARCH = 'productkey';

    /**
     * 产品Id
     */
    protected $PId;
    /**
     * 缓存的KEY
     */
    protected $_cacheKey;
    /**
     * 缓存的数据
     */
    protected $_data;
    /**
     * 缓存实例
     *
     * @var Helper_Cache_Memcache
     */
    protected $_cacheInstance;
    /**
     * 缓存的命名空间
     */
    const CACHE_NS = '_productInfo';

    /**
     * cookie的命名空间
     */
    const COOKIE_NS = 'userInquire';

    /**
     * session的命名空间
     */
    const SESSION_NS = 'userInquire';

    /**
     * 默认推荐产品类型ID
     */
    const PRODUCT_TYPE_RECOMMEND = 1;
    /**
     * 单例对象
     */
    public static $singletonObjects = array();

    /**
     * 
     * 构造器
     */
    private function __construct($PId) {
        $this->PId = $PId;
        $this->_cacheKey = $PId . self::CACHE_NS;
        $this->_cacheInstance = Common::getCache();
        $this->_data = $this->_cacheInstance->get($this->_cacheKey);

        if ($this->_data === false) {
            $this->_loadFromDb();
        }

        if (empty($this->_data)) {
            $this->_data = array();
        }
    }

    /**
     * 获取单例
     * @param $uId 用户ID
     * @return User_Info
     * @throws AppException
     */
    public static function getInstance($PId) {
        $className = __CLASS__;
        if (!isset(self::$singletonObjects[$PId][$className])) {
            self::$singletonObjects[$PId][$className] = new self($PId);
        }

        return self::$singletonObjects[$PId][$className];
    }

    /**
     * 
     * 默认推荐产品信息
     * return array( 
     *  PId      int          产品Id
     *  PName    string       产品名称 
     *  PTtye    int          产品类型
     *  PIc      string       产品图片路径
     * )
     */
    public static function getDefault() {
        $defaultlist = Common::getMySql()->getList(self::TABLE_NAME, array('PType' => self::PRODUCT_TYPE_RECOMMEND));
        return $defaultlist;
    }

    /**
     * 根据产品防伪码查询产品id
     * return array(
     *  PId int 产品ID
     *  Ky  int 产品防伪码
     * )
     */
    public static function getProductId($code) {
        $where = array(
            'Key' => $code
        );

        $productkey = Common::getMySql()->get(self::TABLE_NAME_SEARCH, $where);
        return $productkey;
    }

    /**
     * 获得产品详细内容
     * return array(
     *  Pname   string     产品名称
     *  PId     int        产品Id
     *  Ptype   int        产品类型
     *  PImg    string     产品图片
     * )
     */
    public function getProductInfo($key) {
        $where = array(
            'PId' => $key
        );
        $productInfo = Common::getMySql()->get(self::TABLE_NAME, $where);
        return $productInfo;
    }

    /**
     * 
     * 存储cookie和session()
     * 
     * 
     */
    public function _saveToCookieSession($prodcutInfo) {
         /*
         * 无用户查询记录session，添加一个记录用户查询的session，同时添加cookie
         */
        if (empty($_SESSION[self::SESSION_NS])) {
            $arraySession = array(
                $prodcutInfo['PId'] => array(
                    'Count' => 1,
                    'Date' => date(' Y-m-d H:m:s ', time())
                )
            );
            
            $arraySession = serialize($arraySession);
            $_SESSION[self::SESSION_NS] = $arraySession;
            
             if ( isset ( $_COOKIE [ self::COOKIE_NS ] ) ) {
                $session = unserialize( $_SESSION[self::SESSION_NS] ) ;
                $cookie = unserialize ( stripslashes ( $_COOKIE[self::COOKIE_NS ] ) ) ;
                print_r($cookie);
                $pid = $prodcutInfo['PId'];
                if ( array_key_exists($pid, $cookie) ) {

                   
                    
                   $cookie [$pid][ 'Count'] = $cookie [$pid][ 'Count'] + 1 ;
                   $cookie [$pid][ 'Date'] = date(' Y-m-d H:m:s ', time()) ;
                    
                    $cookie = serialize($cookie) ;

                    setcookie(self::COOKIE_NS, $cookie ,time()+36000) ;
//                    print_r( unserialize( stripslashes ( $_COOKIE[self::COOKIE_NS] ) ) );
                    
                }
                
                else {
                    
                    $cookie[ $pid ] = $session [$pid ] ;
                    $cookie = serialize($cookie) ;
                    setcookie(self::COOKIE_NS, $cookie ,time()+36000) ;
//                    print_r( unserialize( stripslashes ( $_COOKIE[self::COOKIE_NS] ) ));
                }
                
            }
            else{
                setcookie(self::COOKIE_NS, $arraySession ,time()+36000);
            }
            
           // setcookie(self::COOKIE_NS, $arraySession, time() + 3600);
        } else {
            $arraySession = unserialize( stripslashes ( $_SESSION[self::SESSION_NS] ) );
            $arrayCookie  = unserialize( stripslashes  ( $_COOKIE[self::SESSION_NS]) ) ;
            
            /*
             * 有此产品ID存在的session和cookie
             * 更新与此产品ID对应的session和cookie
             */
            if (array_key_exists($prodcutInfo['PId'], $arraySession)) {
                $arraySession [$prodcutInfo['PId']] ['Count'] = $arraySession [$prodcutInfo['PId']] ['Count'] + 1;
                $arraySession [$prodcutInfo['PId']] ['Date'] = date('Y-m-d H:m:s', time());

                $arraySession = serialize($arraySession);
                $_SESSION [self::SESSION_NS] = $arraySession;
                setcookie(self::COOKIE_NS, $_SESSION [self::SESSION_NS], time() + 3600);
            }
            /*
             * 原session用户查询记录无此产品ID，插入此次查询记录
             */ else {
                $arraySession [$prodcutInfo['PId']] =
                        array(
                            'Count' => 1,
                            'Date' => date(' Y-m-d H:m:s ', time())
                );

                $arraySession = serialize($arraySession);

                $_SESSION [self::SESSION_NS] = $arraySession;

                setcookie(self::COOKIE_NS, $_SESSION [self::SESSION_NS], time() + 3600);
            }
            
        }
    }

    /**
     * 产品推送 
     * return array(
     *  pId   int         产品Id
     *  PName string      产品图片
     *  Pic   string      产品图片路径
     * ); 
     *
     */
    public static function productCoommend($searchData) {
        //查询结果数组过滤
        $arrayCount = array();
        foreach ($searchData as $key => $value) {
            $arrayCount[$key] = $value['Count'];
        }
        arsort($arrayCount);

        $arraySlice = array();
        $arraySlice = array_slice($arrayCount, 0, 3, true);

        $arrayPId = array_keys($arraySlice);
        //产品产品推送
        $getProduct = Common::getMysql()->getMultiList(self::TABLE_NAME, 'PId', $arrayPId);
        //是否需要显示默认产品
        $resultProduct = self::selectDefault($getProduct);
        return $resultProduct;
    }

    /**
     * 测试推送产品的数量，判断需要添加的默认产品数量
     * 
     */
    public static function selectDefault($getProduct) {
        $count = count($getProduct);
        if (1 <= $count && $count < 2) {
            $defaultlist = Common::getMySql()->getList(self::TABLE_NAME, array('PType' => self::PRODUCT_TYPE_RECOMMEND), 0, 0, 2);
            return ( array_merge($getProduct, $defaultlist));
        } elseif (2 <= $count && $count < 3) {
            $defaultlist = Common::getMySql()->getList(self::TABLE_NAME, array('PType' => self::PRODUCT_TYPE_RECOMMEND), 0, 0, 1);
            return ( array_merge($getProduct, $defaultlist));
        } else {
            return $getProduct;
        }
    }

    /**
     * 从数据库加载产品的基本信息
     * @return array
     */
    private function _loadFromDb() {
        $productInfo = Common::getMysql()->get(self::TABLE_NAME, array('PId' => $this->PId));

        if ($productInfo == false) {
            echo "该产品不存在";
            //throw new AppException( 5 );
        }
        $this->_data = array(
            'PId' => $productInfo['PId'],
            'PName' => $productInfo['PName'],
            'Pic' => $productInfo['Pic'],
            'Count' => 1
        );
    }
      /**
     * 获取产品信息
     * 
     */
    public static function getProduccInfo($pname) {
        
        $productInfo = Common::getMysql()->get(self::TABLE_NAME, array('PName' => $pname));
        return $productInfo ;
        
    }


}